package com.example.demo.controller;

import com.example.demo.pojo.User;
import com.example.demo.service.JiLueService;
import com.example.demo.service.UserManagementService;
import com.example.demo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.jaxb.SpringDataJaxb;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import static com.example.demo.util.Md5Util.StringInMd5;


@RestController
@RequestMapping("/api/user")
public class UserManagementController {

    @Autowired
    private UserManagementService userManagementService;


   @PostMapping("/list")
    public Map<String, Object> getUserPage(@RequestBody Map<String, Object> params) {
       Map<String, Object> innerParams = (Map<String, Object>) params.get("params");

    // 获取参数并设置默认值
        String nickname = (String) innerParams.getOrDefault("nickname", "");
        int current = (int) innerParams.getOrDefault("current", 1);  // 默认第一页
        int size = (int) innerParams.getOrDefault("size", 10);       // 默认每页10条

        // 打印调试信息
        System.out.println("Params: " + innerParams);
        System.out.println("Nickname: " + nickname);
        System.out.println("Current Page: " + current);
        System.out.println("Page Size: " + size);
       List<User> user = userManagementService.selectUser(nickname);

       int length = user.size();
       // 构造模拟数据
       Map<String, Object> response = new HashMap<>();
response.put("result", Map.of(
    "records", user, // 直接使用 user 列表
    "current", (int)(length / size) + 1, // 假设 current 是一个已经定义的变量，表示当前页码
    "size", size, // 假设 size 是一个已经定义的变量，表示每页大小
    "total", length // 假设 total 是一个已经定义的变量，表示总记录数
));

        System.out.println("Response Data: " + response); // 打印日志
        return ResponseEntity.ok(response).getBody();
    }

    @PostMapping("/add")
    public String addUser(@RequestBody User user) {
        user.setPassword(StringInMd5(user.getPassword()));
        int result = userManagementService.addUser(user);
        System.out.println("添加成功");
        return result > 0 ? "添加成功" : "添加失败";
    }

    @DeleteMapping("/deleteUser/{id}")
    public String deleteUser(@PathVariable Long id) {
        int result = userManagementService.deleteUser(id);
        return result > 0 ? "删除成功" : "删除失败";
    }

    @PutMapping("/update")
    public String updateUser(@RequestBody User user) {
        int result = userManagementService.updateUser(user);
        return result > 0 ? "更新成功" : "更新失败";
    }
}

